﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections.Specialized;
using XentrixModules;

public partial class User_Controls_Modal_SearchDepartment : System.Web.UI.UserControl
{
    public delegate void DepartmentSelectionEventHandler(object sender, DepartmentSelectionArgs e);
    public event DepartmentSelectionEventHandler DepartmentSelected;

    public EventHandler Closed;

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void XRCSearchDepartmentOuter_Closing(object sender, EventArgs e)
    {
        if (Closed != null)
        {
            Closed(this, e);
        }
    }

    public void Show()
    {
        XRCSearchDepartmentOuter.Show();
    }

    public void Hide()
    {
        XRCSearchDepartmentOuter.Hide();
    }

    protected void XRCBSearchDepartment_Click(object sender, EventArgs e)
    {
        using (SqlEngine SqlEngine = new SqlEngine("AssetTracking"))
        {
            SqlEngineProcedureVariable[] var = { new SqlEngineProcedureVariable("@Department",TextBoxDepartment.Text),
                                                         new SqlEngineProcedureVariable("@Directorate",TextBoxDirectorateCostCentre.Text)};
            DataTable DTDepartmentResults = SqlEngine.ExecuteProcedure("Search_Departments", var);

            GridViewSearchResults.DataSource = DTDepartmentResults;
            GridViewSearchResults.DataBind();
        }
    }

    protected void GridViewDepartmentSearchResults_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        IOrderedDictionary keys = GridViewSearchResults.DataKeys[e.NewSelectedIndex].Values;

        TriggerSelectionEvent(sender, keys[0].ToString(), keys[1].ToString());
        this.Hide();
    }

    private void TriggerSelectionEvent(object sender, string DepartmentName, string Directorate)
    {
        DepartmentSelectionArgs ArgsToSend = new DepartmentSelectionArgs();
        ArgsToSend.DepartmentName = DepartmentName.ToString();
        ArgsToSend.Directorate = Directorate.ToString();

        if (DepartmentName != null)
        {
            DepartmentSelected(sender, ArgsToSend);
        }
        else
        {
            throw new Exception("Silly fool implement the 'OnPersonSelectedEvent!'");
        }
    }

    public class DepartmentSelectionArgs : EventArgs
    {
        public string DepartmentName;
        public string Directorate;
    }

  

    public void ClearFields()
    {
        throw new NotImplementedException();
    }
}
